<template>
    <div class="activity-detail">
        <div v-loading="loading" class="detail-container">
            <el-card class="detail-card">
                <!-- 活动基本信息 -->
                <div class="activity-header">
                    <div class="header-content">
                        <h1 class="activity-title">{{ activityInfo.title }}</h1>
                        <div class="activity-meta">
                            <el-tag :type="getTypeTagType(activityInfo.activityType)" size="medium">
                                {{ getTypeLabel(activityInfo.activityType) }}
                            </el-tag>
                            <el-tag :type="getStatusTagType(activityInfo.status)" size="medium"
                                style="margin-left: 10px;">
                                {{ getStatusLabel(activityInfo.status) }}
                            </el-tag>
                            <el-tag :type="getRegistrationStatusTagType(activityInfo)" size="medium"
                                style="margin-left: 10px;">
                                {{ getRegistrationStatusLabel(activityInfo) }}
                            </el-tag>
                        </div>
                    </div>
                </div>

                <!-- 活动详细信息 -->
                <div class="activity-content">
                    <el-row :gutter="20">
                        <el-col :span="16">
                            <div class="content-section">
                                <h3>活动内容</h3>
                                <div class="description">
                                    {{ activityInfo.content }}
                                </div>
                            </div>

                            <div v-if="activityInfo.requirements" class="content-section">
                                <h3>参与要求</h3>
                                <div class="requirements">
                                    {{ activityInfo.requirements }}
                                </div>
                            </div>

                            <div v-if="activityInfo.poster" class="content-section">
                                <h3>活动海报</h3>
                                <el-image :src="activityInfo.poster" :preview-src-list="[activityInfo.poster]"
                                    fit="contain" class="poster-image" />
                            </div>

                            <div v-if="activityInfo.attachmentUrl && activityInfo.attachmentUrl.length > 0"
                                class="content-section">
                                <h3>活动附件</h3>
                                <div class="schedule-files">
                                    <div v-for="(file, index) in activityInfo.attachmentUrl" :key="index"
                                        class="file-item" @click="handleDownloadFile(file)">
                                        <i :class="getFileIcon(file.name)" class="file-icon" />
                                        <span class="file-name">{{ file.name }}</span>
                                        <span class="file-size">{{ formatFileSize(file.size) }}</span>
                                        <el-button type="text" size="small" class="download-btn">
                                            <i class="el-icon-download" />
                                            下载
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </el-col>

                        <el-col :span="8">
                            <div class="info-panel">
                                <div class="info-item">
                                    <i class="el-icon-time info-icon" />
                                    <div class="info-content">
                                        <div class="info-label">活动时间</div>
                                        <div class="info-value">
                                            {{ activityInfo.startTime | parseTime('{y}-{m}-{d} {h}:{i}') }} -
                                            {{ activityInfo.endTime | parseTime('{y}-{m}-{d} {h}:{i}') }}
                                        </div>
                                    </div>
                                </div>

                                <div class="info-item">
                                    <i class="el-icon-location-outline info-icon" />
                                    <div class="info-content">
                                        <div class="info-label">活动地点</div>
                                        <div class="info-value">{{ activityInfo.location }}</div>
                                    </div>
                                </div>

                                <div class="info-item">
                                    <i class="el-icon-user info-icon" />
                                    <div class="info-content">
                                        <div class="info-label">发布者</div>
                                        <div class="info-value">{{ activityInfo.publishName }}</div>
                                    </div>
                                </div>

                                <div class="info-item">
                                    <i class="el-icon-phone info-icon" />
                                    <div class="info-content">
                                        <div class="info-label">联系方式</div>
                                        <div class="info-value">{{ activityInfo.phone }}</div>
                                    </div>
                                </div>

                                <div class="info-item">
                                    <i class="el-icon-date info-icon" />
                                    <div class="info-content">
                                        <div class="info-label">报名截止</div>
                                        <div class="info-value">
                                            {{ activityInfo.registrationDeadline | parseTime('{y}-{m}-{d} {h}:{i}') }}
                                        </div>
                                    </div>
                                </div>

                                <div class="info-item">
                                    <i class="el-icon-s-data info-icon" />
                                    <div class="info-content">
                                        <div class="info-label">报名情况</div>
                                        <div class="info-value">
                                            {{ activityInfo.currentParticipants }}/{{ activityInfo.maxParticipants ||
                                                '不限'
                                            }}
                                            <el-progress v-if="activityInfo.maxParticipants"
                                                :percentage="getRegistrationProgress()" :stroke-width="6"
                                                style="margin-top: 5px;" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script>
import { parseTime } from '@/utils'
import { getActivityDetail } from '@/api/activity'
export default {
    name: 'ActivityDetail',
    filters: {
        parseTime
    },
    data() {
        return {
            loading: true,
            activityInfo: {},
            participantsList: [],
            userInfo: {} // 当前用户信息
        }
    },
    computed: {
        isPublisher() {
            return this.userInfo.id === this.activityInfo.creatorId
        }
    },
    created() {
        this.getActivityDetail();
    },
    methods: {
        async getActivityDetail() {
            const activityId = this.$route.params.id
            this.loading = true;
            try {
                const res = await getActivityDetail(activityId);
                res.data.attachmentUrl = JSON.parse(res.data.attachmentUrl || '[]');
                this.activityInfo = res.data;
                this.loading = false;
            } catch (error) {
                console.error(error);
            } finally {
                this.loading = false;
            }
        },
        checkUserRegistration() {
            // TODO: 检查用户是否已报名此活动
            // activityApi.checkUserRegistration(this.activityInfo.id).then(response => {
            //   this.userRegistration = response.data
            // })

            // 模拟数据
            this.userRegistration = null // 未报名
        },
        getParticipantsList() {
            // TODO: 获取参与者列表（仅发布者可见）
            this.participantsList = [
                {
                    username: '张三',
                    account: '2021001',
                    phone: '13800138001',
                    department: '计算机学院',
                    registrationTime: '2025-10-25 10:30:00'
                },
                {
                    username: '李四',
                    account: '2021002',
                    phone: '13800138002',
                    department: '软件学院',
                    registrationTime: '2025-10-25 11:15:00'
                }
            ]
        },
        handleExportParticipants() {
            // TODO: 导出参与者名单
            this.$message({
                type: 'success',
                message: '名单导出成功！'
            })
        },
        getRegistrationProgress() {
            if (!this.activityInfo.maxParticipants) return 0
            return Math.round((this.activityInfo.currentParticipants / this.activityInfo.maxParticipants) * 100)
        },
        handleDownloadFile(file) {
            // TODO: 实现文件下载功能
            if (file.url) {
                // 创建一个临时的a标签进行下载
                const link = document.createElement('a')
                link.href = file.url
                link.download = file.name
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)

                this.$message.success('文件下载开始')
            } else {
                this.$message.error('文件链接不存在')
            }
        },
        getFileIcon(fileName) {
            const ext = fileName.split('.').pop().toLowerCase()
            const iconMap = {
                pdf: 'el-icon-document',
                doc: 'el-icon-document',
                docx: 'el-icon-document',
                xls: 'el-icon-s-grid',
                xlsx: 'el-icon-s-grid',
                ppt: 'el-icon-picture-outline',
                pptx: 'el-icon-picture-outline'
            }
            return iconMap[ext] || 'el-icon-document'
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 B'
            const k = 1024
            const sizes = ['B', 'KB', 'MB', 'GB']
            const i = Math.floor(Math.log(bytes) / Math.log(k))
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
        },
        getTypeLabel(type) {
            const typeMap = {
                1: '讲座',
                2: '赛事',
                3: '培训',
                // 兼容字符串格式
                lecture: '讲座',
                competition: '赛事',
                training: '培训'
            }
            return typeMap[type] || type
        },
        getTypeTagType(type) {
            const typeMap = {
                1: 'primary',
                2: 'success',
                3: 'warning',
                // 兼容字符串格式
                lecture: 'primary',
                competition: 'success',
                training: 'warning'
            }
            return typeMap[type] || ''
        },
        getStatusLabel(status) {
            const statusMap = {
                1: '发布',
                2: '结束',
                3: '取消',
                // 兼容字符串格式
                registering: '报名中',
                ongoing: '进行中',
                finished: '已结束'
            }
            return statusMap[status] || status
        },
        getStatusTagType(status) {
            const statusMap = {
                1: 'success',    // 发布 - 绿色
                2: 'warning',    // 结束 - 橙色
                3: 'danger',     // 取消 - 红色
                // 兼容字符串格式
                registering: 'success',
                ongoing: 'warning',
                finished: 'info'
            }
            return statusMap[status] || ''
        },
        // 获取报名状态标签文本
        getRegistrationStatusLabel(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 如果活动状态不是发布状态，直接返回对应状态
            if (row.status !== 1) {
                return this.getStatusLabel(row.status)
            }

            // 活动已结束
            if (now > endTime) {
                return '已结束'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return '进行中'
            }

            // 报名已截止但活动未开始
            if (now > registrationDeadline && now < startTime) {
                return '报名截止'
            }

            // 报名中
            if (now <= registrationDeadline) {
                // 检查是否已满员
                if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                    return '已满员'
                }
                return '报名中'
            }

            return '未知'
        },
        // 获取报名状态标签类型
        getRegistrationStatusTagType(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 如果活动状态不是发布状态
            if (row.status !== 1) {
                return this.getStatusTagType(row.status)
            }

            // 活动已结束
            if (now > endTime) {
                return 'info'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return 'success'
            }

            // 报名已截止但活动未开始
            if (now > registrationDeadline && now < startTime) {
                return 'warning'
            }

            // 报名中
            if (now <= registrationDeadline) {
                // 检查是否已满员
                if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                    return 'danger'
                }
                return 'primary'
            }

            return ''
        }
    }
}
</script>

<style lang="scss" scoped>
.activity-detail {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: calc(100vh - 84px);
}

.detail-container {
    max-width: 1200px;
    margin: 0 auto;
}

.detail-card {
    .activity-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 30px;
        padding-bottom: 20px;
        border-bottom: 1px solid #ebeef5;

        .header-content {
            flex: 1;

            .activity-title {
                font-size: 28px;
                font-weight: bold;
                color: #303133;
                margin: 0 0 15px 0;
                line-height: 1.4;
            }

            .activity-meta {
                display: flex;
                align-items: center;
            }
        }

        .header-actions {
            flex-shrink: 0;
            margin-left: 20px;
        }
    }

    .activity-content {
        .content-section {
            margin-bottom: 30px;

            h3 {
                font-size: 18px;
                font-weight: bold;
                color: #303133;
                margin-bottom: 15px;
                padding-left: 10px;
                border-left: 4px solid #409EFF;
            }

            .description,
            .requirements {
                line-height: 1.8;
                color: #606266;
                font-size: 14px;
                padding: 15px;
                background-color: #f8f9fa;
                border-radius: 6px;
            }

            .poster-image {
                max-width: 100%;
                border-radius: 6px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }
        }
    }
}

.info-panel {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px;

    .info-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 20px;

        &:last-child {
            margin-bottom: 0;
        }

        .info-icon {
            font-size: 18px;
            color: #409EFF;
            margin-right: 12px;
            margin-top: 2px;
            flex-shrink: 0;
        }

        .info-content {
            flex: 1;

            .info-label {
                font-size: 12px;
                color: #909399;
                margin-bottom: 5px;
            }

            .info-value {
                font-size: 14px;
                color: #303133;
                font-weight: 500;
                line-height: 1.4;
            }
        }
    }
}

.participants-card {
    ::v-deep .el-card__header {
        background-color: #f8f9fa;
        border-bottom: 1px solid #ebeef5;
    }
}

.schedule-files {
    .file-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        margin-bottom: 8px;
        background-color: #f8f9fa;
        border: 1px solid #e4e7ed;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
            background-color: #ecf5ff;
            border-color: #409EFF;
        }

        &:last-child {
            margin-bottom: 0;
        }

        .file-icon {
            font-size: 20px;
            color: #409EFF;
            margin-right: 12px;
            flex-shrink: 0;
        }

        .file-name {
            flex: 1;
            font-size: 14px;
            color: #303133;
            font-weight: 500;
            margin-right: 12px;
        }

        .file-size {
            font-size: 12px;
            color: #909399;
            margin-right: 12px;
            flex-shrink: 0;
        }

        .download-btn {
            flex-shrink: 0;
            padding: 0;

            &:hover {
                color: #409EFF;
            }
        }
    }
}
</style>
